const _ = require('lodash');
const { actionNotes, actionItems } = require('./../data/data');
const pageLength = 5;

const resolvers = {
    Query: {
        // page/pageIndex start from 0
        /*
        {
          getActionItems(page: 1) {
            dataCount
            pageIndex
            actionItems{
              id
            }
          }
        }
         */
        getActionItems: (root, { page }) => {
          let pageIndex = (!page) ? 0 : page;
          return {
            actionItems: _.filter(actionItems, (elem, index) => ( parseInt( index / pageLength) == pageIndex)),
            dataCount: actionItems.length,      
            pageLength: pageLength, 
            pageIndex: pageIndex, 
          }      
        },
        getActionItem: (root, { id }) => _.find(actionItems, (elem) => (elem.id == id)),
        getActionNotes: (root, { page }) => {
          let pageIndex = (!page) ? 0 : page;
          return {
            actionNotes: _.filter(actionNotes, (elem, index) => ( parseInt( index / pageLength) == pageIndex)),
            dataCount: actionNotes.length,      
            pageLength: pageLength, 
            pageIndex: pageIndex, 
          }    
        },
        getActionNote: (root, { id }) => _.find(actionNotes, (elem) => (elem.id == id)),
    },
    Mutation: {
      updateActionItem: (root, { id, input }) => {
        let actionItem = _.find(actionItems, (elem) => (elem.id == id));
        if (!actionItem) throw new Error(`Couldn't find the action item.`);
        Object.assign(actionItem, input);
        return actionItem;
      },
      addActionItem: (root, {input}) => {
        let actionItem = {...input, 'id': actionItems.length};
        actionItems.push(actionItem);
        return actionItem;
      },
      updateActionNote: (root, { id, input }) => {
        let actionNote = _.find(actionNotes, (elem) => (elem.id == id));
        if (!actionNote) throw new Error(`Couldn't find the action note.`);
        Object.assign(actionNote, input);
        return actionNote;
      },
      addActionNote: (root, {input}) => {
        let actionNote = {...input, 'id': actionNotes.length};
        actionNotes.push(actionNote);
        return actionNote;
      },
    },
};

module.exports = resolvers;
